<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>MessageChannel - port1</title>
	</head>

	<body>
		<p id="pRef">port1-count：0</p>
		<input type="button" value="点击发送给port2" id="btnRef" />
		<iframe src="./port2.html" id="iframeRef"></iframe>
		<script>
			const pRef = document.querySelector('#pRef')
			const btnRef = document.querySelector('#btnRef')
			const channel = new MessageChannel()
			const port1 = channel.port1
			const iframeRef = document.querySelector('#iframeRef')
			iframeRef.onload = function () {
				// 初始化 port2
				iframeRef.contentWindow.postMessage('init-port2', '*', [
					channel.port2,
				])
			}

			// 监听 port2 发给 port1 的消息
			port1.onmessage = handleMessage
			function handleMessage(e) {
				pRef.textContent = 'port1-count：' + e.data
			}
			btnRef.addEventListener('click', () => {
				// port1 给 port2 发消息
				port1.postMessage(Math.random())
			})
		</script>
	</body>
</html>
